<template>
  <div class="balance-query-container">
    <!-- 页面标题和状态 -->
    <div class="page-header">
      <h1>账户余额查询</h1>
      <p>实时查看您的账户余额及交易记录</p>
    </div>

    <!-- 余额展示卡片 -->
    <el-card class="balance-card" shadow="hover">
      <div class="balance-header">
        <div class="balance-title">当前账户余额</div>
        <div class="balance-status">
          <el-tag type="success">账户正常</el-tag>
        </div>
      </div>
      <div class="balance-value-container">
        <span class="currency符号">¥</span>
        <span class="balance-value" ref="balanceValue">{{
            formattedBalance
          }}</span>
      </div>
      <div class="balance-subtitle">最后更新: {{ lastUpdateTime }}</div>
    </el-card>

    <!-- 账户信息和操作 -->
    <el-row :gutter="20" class="account-info-row">
      <el-col :span="12">
        <el-card class="info-card" shadow="hover">
          <div class="card-title">账户信息</div>
          <div class="info-list">
            <div class="info-item">
              <span class="info-label">卡号:</span>
              <span class="info-value">{{ maskedCardNumber }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">账户类型:</span>
              <span class="info-value">{{ accountType }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">开户日期:</span>
              <span class="info-value">{{ openDate }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="action-card" shadow="hover">
          <div class="card-title">快捷操作</div>
          <div class="action-buttons">
            <el-button type="primary" icon="Plus" @click="handleDeposit"
            >存款</el-button
            >
            <el-button type="warning" icon="Minus" @click="handleWithdraw"
            >取款</el-button
            >
            <el-button type="info" icon="Switch" @click="handleTransfer"
            >转账</el-button
            >
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近交易记录 -->
    <el-card class="transaction-card" shadow="hover">
      <div class="card-header">
        <div class="card-title">最近交易记录</div>
        <el-button size="small" type="text" @click="viewAllTransactions"
        >查看全部 <el-icon><ArrowRight /></el-icon
        ></el-button>
      </div>
      <el-table :data="recentTransactions" stripe style="width: 100%">
        <el-table-column prop="tradeDate" label="日期" width="180">
          <template #default="{ row }">
            {{ formatDate(row.tradeDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="tradeType" label="交易类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.tradeType === '存款' ? 'success' : 'danger'">{{
                row.tradeType
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tradeMoney" label="金额" width="120">
          <template #default="{ row }">
            <span
                :class="
                row.tradeType === '存款' ? 'positive-amount' : 'negative-amount'
              "
            >
              {{ row.tradeType === "存款" ? "+" : "-" }}{{ row.tradeMoney }}
            </span>
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--            prop="balance"-->
<!--            label="交易后余额"-->
<!--            width="180"-->
<!--        ></el-table-column>-->
        <el-table-column prop="remark" label="交易描述"></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ArrowRight } from "@element-plus/icons-vue";
import numeral from "numeral"; // 用于数字格式化
import axios from "axios";

// 获取路由实例
const router = useRouter();

// 账户数据
const balance = ref(0);
const maskedCardNumber = ref("");
const accountType = ref("");
const openDate = ref("");
const lastUpdateTime = ref("");

// 最近交易记录
const recentTransactions = ref([]);

// 格式化余额显示
const formattedBalance = ref("");

// DOM 引用
const balanceValue = ref(null);

// 当前用户名
const username = ref(localStorage.getItem("username") || "");

// 数字滚动动画
const animateNumber = (element, target, duration = 1000) => {
  const start = 0;
  const increment = target / (duration / 16);
  let current = start;

  const timer = setInterval(() => {
    current += increment;
    if (current >= target) {
      current = target;
      clearInterval(timer);
    }
    element.textContent = numeral(current).format("0,0.00");
  }, 16);
};

// 打开存款页面
const handleDeposit = () => {
  router.push({ name: "Transaction" });
};

// 打开取款页面
const handleWithdraw = () => {
  router.push({ name: "Transaction" });
};

// 打开转账页面
const handleTransfer = () => {
  router.push({ name: "Transfer" });
};

// 查看全部交易记录
const viewAllTransactions = () => {
  console.log("查看全部交易记录");
  // 这里可以添加跳转逻辑
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取数据
const fetchData = async () => {
  try {
    // 设置最后更新时间为当前时间
    lastUpdateTime.value = new Date().toLocaleString();

    // 使用后端接口获取账户余额
    const balanceResponse = await axios.get(
        `http://localhost:8088/api/cards/totalBalance?username=${username.value}`
    );
    balance.value = balanceResponse.data;

    // 页面加载时执行数字滚动动画
    if (balanceValue.value) {
      animateNumber(balanceValue.value, balance.value);
    }

    // 获取卡片信息列表的第一个卡片
    const cardResponse = await axios.get(
        `http://localhost:8088/api/cards/user?username=${username.value}`
    );
    const cardList = cardResponse.data;
    if (cardList.length > 0) {
      const firstCard = cardList[0];
      // 使用第一个卡片的卡号获取交易信息
      const transactionResponse = await axios.get(
          `http://localhost:8088/api/transactions/select1/${firstCard.cardID}`
      );
      console.log(transactionResponse);
      const transactions = transactionResponse.data;

      // 更新账户信息和交易记录
      maskedCardNumber.value = firstCard.cardID; // 填入卡号
      accountType.value = firstCard.curID; // 将 curid 值填入账户类型
      openDate.value = firstCard.openDate;

      // 假设 recentTransactions 是从 transaction 数据中获取的
      recentTransactions.value = transactions;

      // 格式化余额显示
      formattedBalance.value = numeral(balance.value).format("0,0.00");
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  }
};

onMounted(() => {
  fetchData();
});
</script>



<style scoped>
/* 样式保持不变 */
.balance-query-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
}

.balance-card {
  background: linear-gradient(135deg, #165dff 0%, #00b4ff 100%);
  color: white;
  border-radius: 12px;
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
}

.balance-card::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 30%;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px 12px 0 0;
}

.balance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  position: relative;
  z-index: 1;
}

.balance-title {
  font-size: 18px;
  font-weight: 500;
}

.balance-status {
  background-color: rgba(255, 255, 255, 0.2);
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 14px;
}

.balance-value-container {
  display: flex;
  align-items: baseline;
  justify-content: center;
  padding: 30px 20px 20px;
  position: relative;
  z-index: 1;
}

.currency符号 {
  font-size: 24px;
  margin-right: 10px;
}

.balance-value {
  font-size: 48px;
  font-weight: 700;
  letter-spacing: 2px;
}

.balance-subtitle {
  text-align: center;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.account-info-row {
  margin-bottom: 20px;
}

.info-card,
.action-card {
  height: 100%;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.card-title i {
  margin-right: 8px;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.info-label {
  color: #606266;
  font-size: 14px;
}

.info-value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.action-buttons .el-button {
  height: 50px;
  border-radius: 8px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.transaction-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.positive-amount {
  color: #00b42a;
  font-weight: 500;
}

.negative-amount {
  color: #f53f3f;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .balance-value {
    font-size: 36px;
  }

  .account-info-row {
    flex-direction: column;
  }

  .el-col {
    width: 100% !important;
  }
}
</style>